<?php
require_once 'model/Model.php';
require_once 'vo/OrderVO.php';

class Order extends Model
{
	private static $instance;
	private $table = "`order`";
	
	public function __construct()
	{
		parent::__construct();
	}
	public function getInstance()
	{
		if(empty(self::$instance))
		{
			self::$instance = new Order();
		}
		return self::$instance;
	}
	
	
	/**
	 * Recebe o pedido, salva e retorna o pedido salvo
	 */	
	public function saveOrder(OrderVO $order)
	{
		$query = "INSERT INTO $this->table (products, price_total) 
					VALUES ('$order->products', '$order->price_total')";
		
		$result = mysql_query($query);
		
		if ($result != FALSE) 
		{
			return $this->loadOrder(mysql_insert_id());
		}
		return false;
	}
	
	
	/**
	 * Recebe o pedido, atualiza e retorna o pedido atualizado
	 */	
	
	public function updateOrder(OrderVO $pedido)
	{
		$query = "UPDATE $this->table SET products = '$order->products', price_total = '$order->price_total' WHERE idOrder = '$order->idOrder'";
		
		$result = mysql_query($query);
		
		if ($result != FALSE) 
		{
			return $this->loadOrder($order->idOrder);
		}
		return false;
	}
	
	
	/**
	 * Retorna todos os produtos
	 */
	public function listOrder()
	{
		$query = "SELECT * FROM $this->table ORDER BY products";
		
		$result = mysql_query($query);
		
		if (($result != FALSE) && (mysql_num_rows($result) > 0))
		{
			while ($item = mysql_fetch_object($result, 'OrderVO'))
				$dataProvider[] = $item;
			return $dataProvider;
		}
		return false;
	}
	
	
	/**
	 * Recebe o idPedido e remove o pedido
	 */
	public function deleteOrder($idPedido)
	{
		$query = "DELETE FROM $this->table WHERE idOrder = '$idOrder'";
		
		$result = mysql_query($query);
		
		if ($result != FALSE) 
		{
			return true;
		}
		return false;
	}
	
	
	/**
	 * Recebe o pedido e retorna os pedidos
	 */
	public function searchOrder($idOrder)
	{
		$query = "SELECT * FROM $this->table WHERE idOrder  = '$idOrder' ORDER BY products";
		
		$result = mysql_query($query);
		
		if (($result != FALSE) && (mysql_num_rows($result) > 0))
		{
			while ($item = mysql_fetch_object($result, 'OrderVO'))
				$dataProvider[] = $item;
			return $dataProvider;
		}
		return false;
	}
	
	
	/**
	 * Recebe o idPedido e retorna todos os pedidos
	 */
	public function loadOrder($idOrder)
	{
		$query = "SELECT * FROM $this->table WHERE idOrder = '$idOrder'";
		
		$result = mysql_query($query);
		if ($result != FALSE)
		{
			return mysql_fetch_object($result, 'OrderVO');			
		}
		return false;
	}	
}